<template>
  <Codemirror :value="codeValue" :options="options" class="common-code" />
</template>

<script lang="ts">
import { defineComponent, reactive, computed, toRefs, onBeforeMount } from 'vue'
import Codemirror from 'codemirror-editor-vue3'
import 'codemirror/mode/javascript/javascript.js' // language
export default defineComponent({
  name: 'CodePreview',
  components: {
    Codemirror
  },
  props: {
    viewFileUrl: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    const state = reactive({
      mode: 'text/javascript',
      codeValue: ''
    })

    const options = computed(() => {
      return {
        value: '',
        tabSize: 2,
        mode: state.mode,
        matchBrackets: true,
        lineNumbers: false,
        lineWrapping: 'wrap',
        line: true,
        addModeClass: true,
        forceBreak: true,
        readOnly: true,
        showCursorWhenSelecting: true,
        theme: 'default'
      }
    })

    onBeforeMount(() => {
      urlToBlob()
    })

    const urlToBlob = () => {
      fetch(props.viewFileUrl, {
        method: 'GET'
      })
        .then((res) => {
          return res.blob()
        })
        .then((blob) => {
          // 获取mode类型
          state.mode = blob.type
          // markdown格式返回
          if (state.mode === 'application/octet-stream') {
            state.mode = 'markdown'
          }
          // 读取文件流
          const reader = new FileReader()
          reader.onload = () => {
            state.codeValue = reader.result + ''
            // 默认使用utf-8转码 如果出现乱码的情况 使用GB2312转码
            if (state.codeValue.includes('�')) {
              reader.readAsText(blob, 'GB2312')
              reader.onload = () => {
                state.codeValue = reader.result + ''
              }
            }
          }
          reader.readAsText(blob)
        })
    }

    return {
      options,
      ...toRefs(state)
    }
  }
})
</script>

<style lang="stylus" scoped>
.common-code {
	max-width calc(100vw - 520px)
	max-height calc(100vh - 228px)
	overflow auto
	border-radius 4px
	:deep(.CodeMirror) {
		background rgba(0, 0, 0, 0.03) !important
		text-align: left;
		position relative
		overflow hidden
		background white
		padding 5px 5px 5px
		position relative
		cursor text
		border-radius 4px
		padding-right 32px
		height 100%
		color #000
		font-size 14px
		line-height 20px
	}
}
.custome-code {
  :deep(.CodeMirror) {
		height 100%
	}
}
</style>
